<template>
    <div class="grid grid-cols-2 h-screen">
        <div class="col-span-2 order-2 md:col-span-1 md:order-1 bg-slate-900">
            <div
                class="flex justify-center items-center h-full flex-col animate__animated animate__bounceInLeft animate__fast">
                <h2 class="flex justify-center items-center h-full flex-col">Weblog 博客登录</h2>
                <p class="text-white">一款由 Spring Boot + Mybaits Plus + Vue 3.2 + Vite 4 开发的前后端分离博客。</p>
                <img src="@/assets/developer.png" alt="w-1/2">
            </div>
        </div>
        <div class="flex flex-col col-span-2 order-1 md:col-span-1 md:order-2 bg-white dark:bg-gray-800">
            <!-- 白天黑夜开关，ml-auto 靠右显示 -->
            <label class="switch ml-auto mt-4 mr-4">
                <input type="checkbox" v-model="isLight" @click="toggleDark()">
                <span class="slider"></span>
            </label>
            <div
                class="flex justify-center items-center h-full flex-col animate__animated animate__bounceInRight animate__fast">
                <h1 class="font-bold text-4xl mb-5 dark:text-white">欢迎回来</h1>
                <div class="flex items-center justify-center mb-7 text-gray-400 space-x-2 dark:text-gray-500">
                    <span class="h-[1px] w-16 bg-gray-200 dark:bg-gray-700"></span>
                    <span>账号密码登录</span>
                    <span class="h-[1px] w-16 bg-gray-200 dark:bg-gray-700"></span>
                </div>
                <el-form class="w-5/6 md:w-2/5" ref="fromRef" :rules="rules" :model="from">
                    <el-form-item prop="username">
                        <el-input size="large" v-model="from.username" placeholder="请输入用户名" :prefix-icon="User"
                            clearable />
                    </el-form-item>
                    <el-form-item prop="password">
                        <el-input size="large" type="password" v-model="from.password" placeholder="请输入密码"
                            :prefix-icon="Lock" clearable show-password />
                    </el-form-item>
                    <el-form-item>
                        <el-button class="w-full mt-2" size="large" :loading="loading" type="primary"
                            @click="onSubmit">登录</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>
    </div>
</template>

<script setup>
import { User, Lock, Loading } from '@element-plus/icons-vue'
import { login } from "@/api/admin/user"
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { showMessage } from '@/composables/util'
import { setToken } from '@/composables/cookie'
import { useUserStore } from '@/stores/user'
import { useDark, useToggle } from '@vueuse/core'

const router = useRouter()
// 全局用户状态
const userStore = useUserStore()

// 是否是白天
const isLight = ref(true)
const isDark = useDark({
    onChanged(dark) {
        console.log('onChanged:' + dark)
        if (dark) {
            document.documentElement.classList.add('dark');
            isLight.value = false
        } else {
            document.documentElement.classList.remove('dark');
            isLight.value = false
        }
    },
})

const toggleDark = useToggle(isDark)

//响应式登录表单对象
const from = reactive({
    username: '',
    password: ''
})

// 表单引用
const fromRef = ref(null)
// 表单验证规则
const rules = {
    username: [
        {
            required: true,
            message: '用户名不能为空',
            trigger: 'blur',
        }
    ],
    password: [
        {
            required: true,
            message: '密码不能为空',
            trigger: 'blur',
        }
    ]
}

// 登录按钮加载
const loading = ref(false)

const onSubmit = () => {
    console.log('登录')
    fromRef.value.validate((valid) => {
        if (!valid) {
            console.log('表单验证没通过')
            return false
        }

        //开始加载
        loading.value = true

        //调用登录接口
        login(from.username, from.password).then((res) => {
            console.log(res)
            if (res.success == true) {
                //提示登录成功
                showMessage('登录成功')

                //存储 Token 到本地
                let token = res.data.token
                setToken(token)

                // 获取用户状态存储到全局状态中
                userStore.setUserInfo()

                //跳转后台首页
                router.push('/admin/index')
            } else {
                // 获取服务端返回的错误信息
                let message = res.message

                //提示信息
                showMessage(message, 'error')
            }
        }).finally(() => {
            loading.value = false
        })
    })

}

//回车键直接提交
function onKeyUp(e) {
    console.log(e)
    if (e.key == 'Enter') {
        onSubmit()
    }
}

//添加键盘监听
onMounted(() => {
    console.log('添加键盘监听')
    document.addEventListener('keyup', onKeyUp)
})

//移除键盘监听
onBeforeUnmount(() => {
    document.removeEventListener('keyup', onKeyUp)
})
</script>

<style>
/* The switch - the box around the slider */
.switch {
  font-size: 17px;
  position: relative;
  display: inline-block;
  width: 3.5em;
  height: 2em;
}

/* Hide default HTML checkbox */
.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

/* The slider */
.slider {
  --background: #28096b;
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: var(--background);
  transition: .5s;
  border-radius: 30px;
}

.slider:before {
  position: absolute;
  content: "";
  height: 1.4em;
  width: 1.4em;
  border-radius: 50%;
  left: 10%;
  bottom: 15%;
  box-shadow: inset 8px -4px 0px 0px #fff000;
  background: var(--background);
  transition: .5s;
}

input:checked + .slider {
  background-color: #522ba7;
}

input:checked + .slider:before {
  transform: translateX(100%);
  box-shadow: inset 15px -4px 0px 15px #fff000;
}
</style>